package com.yjzx.util.service.aop.ref.obj;

import com.yjzx.util.service.aop.ref.obj.cache.InterfaceCache;
import com.yjzx.util.service.aop.ref.obj.enums.CacheTypeEnum;
import com.yjzx.util.service.aop.ref.obj.event.CacheEvent;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @author guozhi
 * @date 2024/10/30
 * @description 缓存事件监听处理
 */
@Component
@RequiredArgsConstructor
public class CacheListener implements ApplicationListener<CacheEvent<?>> {
    private final Set<InterfaceCache<?>> cacheEventList;

    public void addAll(InterfaceCache<?>... cache) {
        cacheEventList.addAll(Arrays.asList(cache));
    }

    public List<InterfaceCache<?>> getCache(String cacheName) {
        List<InterfaceCache<?>> list = new ArrayList<>();
        for (InterfaceCache<?> cache : cacheEventList) {
            if (Objects.equals(cacheName, cache.getCacheName())) {
                list.add(cache);
            }
        }
        return list;
    }

    public InterfaceCache<?> getCache(String cacheName, CacheTypeEnum cacheType) {
        for (InterfaceCache<?> cache : cacheEventList) {
            if (Objects.equals(cacheName, cache.getCacheName()) && Objects.equals(cache.getCacheType(), cacheType)) {
                return cache;
            }
        }
        return null;
    }

    @Override
    public void onApplicationEvent(CacheEvent<?> cacheEvent) {
        for (InterfaceCache<?> cache : cacheEventList) {
            if (cacheEvent.supports(cache.getCacheName())) {
                switch (cacheEvent.getOperate()) {
                    case get:
                        cache.select(cacheEvent);
                        break;
                    case PUT:
                        cache.put(cacheEvent);
                        break;
                    case PUT_ALL:
                        cache.putAll(cacheEvent);
                        break;
                    case REMOVE:
                        cache.remove(cacheEvent);
                        break;
                    case REMOVES:
                        cache.removes(cacheEvent);
                        break;
                    case CLEAR:
                        cache.clear(cacheEvent);
                        break;
                    default:
                }
            }
        }

    }
}
